package com.young.nyd.web;

import com.young.common.client.ums.UmsClientHelper;
import com.young.common.core.excel.ExcelExport;
import com.young.common.core.excel.ExcelImport;
import com.young.common.core.excel.IExcelExport;
import com.young.common.core.excel.IExcelImport;
import com.young.common.util.CommonUtil;
import com.young.common.util.Result;
import com.young.common.util.StringUtils;
import com.young.common.util.Page;
import com.young.interfaces.log.annotation.Log;
import com.young.nyd.model.CollaboratMonitoring;
import com.young.nyd.model.CollaboratSample;
import com.young.nyd.service.ICollaboratMonitoringService;
import com.young.nyd.service.ICollaboratSampleService;
import com.young.ums.model.Dept;
import com.young.ums.model.Role;
import com.young.ums.model.RoleUser;
import com.young.ums.model.User;
import com.young.ums.service.IDeptService;
import com.young.ums.service.IRoleService;
import com.young.ums.service.IRoleUserService;
import com.young.ums.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
* 协同监测样点服务
* Created by  on 2018-11-5.
*/
@Controller
@RequestMapping("/nyd/collaboratMonitoring")
public class CollaboratMonitoringController {

    @Resource(name="collaboratMonitoringService")
    ICollaboratMonitoringService service;

    @Resource(name="collaboratSampleService")
    ICollaboratSampleService collaboratSampleService;

    @Resource(name="userService")
   IUserService userService;
    @Resource(name="roleUserService")
    IRoleUserService roleUserService;

    @Resource(name="deptService")
    IDeptService deptService;

    @Resource(name="roleService")
    IRoleService roleService;

    CollaboratMonitoring exportList = null;

    public CollaboratMonitoring selectListByUserxzqu(CollaboratMonitoring obj){
        com.young.interfaces.ums.model.User loginUser = UmsClientHelper.getLoginUser();//已登陆用户
        if(loginUser == null){
            return  null;
        }else {
            String companyId = loginUser.getCompanyId();
            Pattern pattern = Pattern.compile("[0-9]*");
            boolean isNumber = pattern.matcher(companyId).matches();
            if (companyId.equals("ROOT")) {

            } else if (companyId.length() == 6 && isNumber) {
                if (companyId.substring(2).equals("0000")) {//省
                    obj.setRegions(companyId.substring(0, 3));
                } else if (companyId.substring(4).equals("00")) {//市
                    obj.setRegions(companyId.substring(0, 4));
                } else {//县
                    obj.setRegions(companyId);
                }
            }
            return  obj;
        }
    }

    /**
     * 获取数据列表
     * @param obj
     * @param request
     * @return
     */
    @Log("查询协同监测样点列表")
    @RequestMapping("/getList")
    @ResponseBody
    public Object getList(CollaboratMonitoring obj, HttpServletRequest request) {
        CollaboratMonitoring obj1 = selectListByUserxzqu(obj);
        if(obj1==null){
            return Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else {
            List<CollaboratMonitoring> list1 = service.getList(obj1);
            return new Result(list1);
        }


    }

    /**
     * 获取分页数据
     * @param obj
     * @param request
     * @return
     */
    @Log("分页查询协同监测样点列表")
    @RequestMapping("/getPage")
    @ResponseBody
    public Object getPage(CollaboratMonitoring obj, HttpServletRequest request) {
        exportList = obj;
        /*User user = new User();
        user.setState(new Integer("1"));

        List<User> list = userService.getList(user);
        for(User u : list){
            String name = u.getName();
            if(name.length()==6){
                //管理
                if(name.substring(3).equals("000")){
                    //省
                    RoleUser roleUser = new RoleUser();
                    roleUser.setId(CommonUtil.getUUID());
                    roleUser.setUserId(u.getId());
                    roleUser.setRoleId("20001000");
                    roleUserService.insert(roleUser);
                }else if(name.substring(4).equals("00")){
                    //市
                    RoleUser roleUser = new RoleUser();
                    roleUser.setId(CommonUtil.getUUID());
                    roleUser.setUserId(u.getId());
                    roleUser.setRoleId("30001000");
                    roleUserService.insert(roleUser);
                }else {
                    //市
                    RoleUser roleUser = new RoleUser();
                    roleUser.setId(CommonUtil.getUUID());
                    roleUser.setUserId(u.getId());
                    roleUser.setRoleId("40001000");
                    roleUserService.insert(roleUser);
                }
            }else if(name.length()==10){
                //非管理
                if(name.substring(6,9).equals("100")){
                    //环保
                    if(name.substring(3).equals("000")){
                        //省
                        RoleUser roleUser = new RoleUser();
                        roleUser.setId(CommonUtil.getUUID());
                        roleUser.setUserId(u.getId());
                        roleUser.setRoleId("20002000");
                        roleUserService.insert(roleUser);
                    }else if(name.substring(4).equals("00")){
                        //市
                        RoleUser roleUser = new RoleUser();
                        roleUser.setId(CommonUtil.getUUID());
                        roleUser.setUserId(u.getId());
                        roleUser.setRoleId("30002000");
                        roleUserService.insert(roleUser);
                    }else{
                        //县
                        RoleUser roleUser = new RoleUser();
                        roleUser.setId(CommonUtil.getUUID());
                        roleUser.setUserId(u.getId());
                        roleUser.setRoleId("40002000");
                        roleUserService.insert(roleUser);
                    }
                }else if(name.substring(6,9).equals("200")){
                    //农业
                    if(name.substring(3).equals("000")){
                        //省
                        RoleUser roleUser = new RoleUser();
                        roleUser.setId(CommonUtil.getUUID());
                        roleUser.setUserId(u.getId());
                        roleUser.setRoleId("20003000");
                        roleUserService.insert(roleUser);
                    }else if(name.substring(4).equals("00")){
                        //市
                        RoleUser roleUser = new RoleUser();
                        roleUser.setId(CommonUtil.getUUID());
                        roleUser.setUserId(u.getId());
                        roleUser.setRoleId("30003000");
                        roleUserService.insert(roleUser);
                    }else{
                        //县
                        RoleUser roleUser = new RoleUser();
                        roleUser.setId(CommonUtil.getUUID());
                        roleUser.setUserId(u.getId());
                        roleUser.setRoleId("40003000");
                        roleUserService.insert(roleUser);
                    }
                }
            }
        }
*/

//        //获取省级部门
//        Dept dept = new Dept();
//        dept.setDeptLevel(3);
//        List<Dept> listdept = deptService.getList(dept);
        //获取省级角色
      /*  Role prorole = roleService.get("20001000");//省级管理员
        Role cityrole = roleService.get("20002000");//省级环保员
        Role courole = roleService.get("20003000");//省级农业员
        Role crole = roleService.get("30001000");//市级管理员*/
        //获取市级角色
//        Role r2 = new Role();
//        r2.setId("30002000");
//        Role r3 = new Role();
//        r3.setId("30003000");
//        Role r4 = new Role();
//        r4.setId("40001000");
//获取县级级角色
//        Role r2 = new Role();
//        r2.setId("40002000");
//        Role r3 = new Role();
//        r3.setId("40003000");
//        List<Role> cityrole =  roleService.getList(r2);
//        List<Role> courole =  roleService.getList(r3);
//
//
//        //循环添加
//        for(Dept d : listdept){
//            String id = d.getId();
//            if(id.length()==6){
//
//                cityrole.get(0).setCompanyId(id);
//                courole.get(0).setCompanyId(id);
//                roleService.insert(cityrole.get(0));
//                roleService.insert(courole.get(0));
//            }
//        }
        CollaboratMonitoring obj1 = selectListByUserxzqu(obj);
        Page page = CommonUtil.getPageFromRequest(request);
        List<CollaboratMonitoring> list1 = service.getPage(obj1, page);
        page.setData(list1);
        return page;
    }

    /**
     * 获取单条数据
     * @param id
     * @param request
     * @return
     */
    @Log("查询协同监测样点")
    @RequestMapping("/get")
    @ResponseBody
    public Object get(String id, HttpServletRequest request) {
        CollaboratMonitoring obj = service.get(id);
        return new Result(obj);
    }

    /**
     * 统计数量18628248580
     * @param obj
     * @param request
     * @return
     */
    @Log("统计协同监测样点数量")
    @RequestMapping("/count")
    @ResponseBody
    public Object count(CollaboratMonitoring obj, HttpServletRequest request) {
        CollaboratMonitoring obj1 =  selectListByUserxzqu(obj);
        return new Result(service.count(obj1));
    }

    /**
     * 新增
     * @param obj
     * @param request
     * @return
     */
    @Log("新增协同监测样点")
    @RequestMapping("/insert")
    @ResponseBody
    public Object insert(CollaboratMonitoring obj, HttpServletRequest request) {
        CollaboratMonitoring  monitoring = new CollaboratMonitoring();
        monitoring.setOrganizationcode(obj.getOrganizationcode());
        List<CollaboratMonitoring> list = service.getList(monitoring);
        if(list.size()==0){
            obj.setRegions(obj.getCounty());
            service.insert(obj);
            return new Result();
        }else{
            return new Result(1,"已存在该样点，无法添加！");
        }

    }

    /**
     * 修改
     * @param obj
     * @param request
     * @return
     */
    @Log("修改协同监测样点")
    @RequestMapping("/update")
    @ResponseBody
    public Object update(CollaboratMonitoring obj, HttpServletRequest request) {
        if(obj.getUnlack().equals("0")){
            service.update(obj);
            return new Result();
        }else{
            return new Result(-1,"信息已锁定，请联系省级管理员解除锁定！方能修改");
        }
    }

    /**
     * 锁定
     * @param ids
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @Log("锁定协同监测样点")
    @RequestMapping("/lock")
    @ResponseBody
    public Object lock(String ids, String id, HttpServletRequest request) throws Exception{
        Result result = new Result();
        CollaboratMonitoring s = new CollaboratMonitoring();
        int i = 0;
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for(String id1 : idArr){
                s.setId(id1);
                s.setUnlack("1");
                i += service.update(s);
            }
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("锁定失败:待锁定编号无效!");
            }
        }else if(StringUtils.isNotBlank(id)){
            s.setId(id);
            s.setUnlack("1");
            i = service.update(s);
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("锁定失败:待锁定编号无效!");
            }
        }else{
            result.setCode(-1);
            result.setInfo("锁定失败:待锁定编号无效!");
        }
        return result;
    }

    /**
     * 解锁
     * @param ids
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @Log("解锁协同监测样点")
    @RequestMapping("/unlock")
    @ResponseBody
    public Object unlock(String ids, String id, HttpServletRequest request) throws Exception{
        Result result = new Result();
        CollaboratMonitoring s = new CollaboratMonitoring();
        int i = 0;
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for(String id1 : idArr){
                s.setId(id1);
                s.setUnlack("0");
                i += service.update(s);
            }
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("解锁失败:待解锁编号无效!");
            }
        }else if(StringUtils.isNotBlank(id)){
            s.setId(id);
            s.setUnlack("0");
            i = service.update(s);
            if(i>=1){
                result.setCode(0);
            }else{
                result.setCode(-1);
                result.setInfo("解锁失败:待解锁编号无效!");
            }
        }else{
            result.setCode(-1);
            result.setInfo("解锁失败:待解锁编号无效!");
        }
        return result;
    }

    /**
     * 删除
     * @param ids
     * @param id
     * @param request
     * @return
     */
    @Log("删除协同监测样点")
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String ids, String id, HttpServletRequest request) {
        Result result = new Result();
        CollaboratSample s = new CollaboratSample();
        boolean flag = false;
        String idarr = "";
        if(StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for(String id1 : idArr){
                CollaboratMonitoring c = service.get(id1);
                s.setPointCode(c.getOrganizationcode());
                List<CollaboratSample> list =  collaboratSampleService.getList(s);
                if(list.size()>0){
                    idarr = id1;
                    flag = false;
                    break;
                }else{
                    flag = true;
                }
            }
            if(!flag){
                result.setCode(-1);
                result.setInfo("删除失败:该"+idarr+"样点下还有数据!应该先删除该样点下数据才能删除");
            }else{
                service.delete(idArr);
            }

        }else if(StringUtils.isNotBlank(id)){
            CollaboratMonitoring c = service.get(id);

            s.setPointCode(c.getOrganizationcode());
           List<CollaboratSample> list =  collaboratSampleService.getList(s);
           if(list.size()>0){
               result.setCode(-1);
               result.setInfo("删除失败:该样点下还有数据!应该先删除该样点下数据才能删除");
           }else{
               service.delete(id);
           }

        }else{
            result.setCode(-1);
            result.setInfo("删除失败:待删除编号无效!");
        }

        return result;
    }

    /**
     * 导入
     * @param file
     * @param request
     * @return
     */
    @Log("导入协同监测样点")
    @RequestMapping("/import")
    @ResponseBody
    public Object importExcel(MultipartFile file, HttpServletRequest request) {
        Result result = new Result();
        try {
            if (file != null && !file.isEmpty()) {
                //excel导入处理,返回excel中的数据集合
                IExcelImport ei = new ExcelImport(file);//将文件转为ExcelImport对象
                //从excel读取数据
                List<CollaboratMonitoring> list = ei.getImportDataAsBean(CollaboratMonitoring.class);
                if (list != null && list.size() > 0){
                    int num = service.batchInsert(list);//批量插入
                    result.setInfo("成功导入数据" + num + "条!");
                }else {
                    result.setCode(-1);
                    result.setInfo("导入失败:excel解析后结果为空!");
                }
            } else {
                result.setCode(-1);
                result.setInfo("导入失败:文件为空!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        }
        return result;
    }

    /**
     * 导出
     * @param obj 查询参数
     * @param request
     * @param response
     * @throws Exception
     */
    @Log("导出协同监测样点")
    @RequestMapping("/export")
    public void exportExcel(CollaboratMonitoring obj, HttpServletRequest request, HttpServletResponse response,String ids) throws Exception {
        List<CollaboratMonitoring> list = new ArrayList<CollaboratMonitoring>();
        if (ids != null && !"".equals(ids)) {
            String[] ids1 = ids.split(",");
            for (String id : ids1) {
                CollaboratMonitoring u = service.get(id);
                list.add(u);
            }
        } else {
            CollaboratMonitoring obj1 = selectListByUserxzqu(obj);
            list = service.getList(obj1);
        }
        if (list != null && list.size() > 0) {
            IExcelExport ee = new ExcelExport();
            ee.insertBeanList(list, CollaboratMonitoring.class);
            ee.write2Response(response, "excel_" + System.currentTimeMillis() + ".xls");
        } else {
            response.getWriter().write("数据为空!");
        }
    }

}